package com.support.base

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.support.net.Http
import com.support.net.Response
import kotlinx.coroutines.launch

/**
 * 页面状态，默认每个页面都拥有状态
 */


open class OurViewModel : ViewModel() {

    private val _toastMsg = MutableLiveData<String>()

    /**
     * toast消息内容
     */
    val toastMsg: LiveData<String> = _toastMsg

    /**
     * loading框
     */
    private val _loadingMsg = MutableLiveData<String>()
    val loadingMsg: LiveData<String> = _loadingMsg

    /**
     * 取消loading框
     */
    private val _dismissLoading = MutableLiveData<Boolean>()
    val dismissLoading: LiveData<Boolean> = _dismissLoading

    /**
     * 初始化
     */
    init {
        inject()
    }

    /**
     * 绑定注入
     */
    private fun inject() {
        Http.inject(this)
    }

    /**
     * 使用协程进行异步请求，并校验请求结果
     */
    protected inline fun <T> verify(
        crossinline suc: (response: T) -> Unit,
        crossinline empty: (empty: String) -> Unit = {},
        crossinline fail: (err: String) -> Unit = {},
        crossinline request: suspend () -> Response<T>
    ) {
        //viewModelScope.launch开启协程，在生命周期结束的时候会自动取消协程任务，保证了内存安全
        viewModelScope.launch {
            try {
                val response: Response<T> = request()
                if (response.code == 1) {
                    if (response.data == null) {
                        empty("暂无数据")
                    } else {
                        suc(response.data)
                    }
                } else {
                    fail(response.msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                fail("服务异常")
            }
        }
    }

    /**
     * 弹出toast,通过liveData项ui层发送消息，弹出消息通知
     *
     */
    fun showToast(msg: String) {
        _toastMsg.postValue(msg)
    }

    /**
     * 弹出loading框
     */
    fun showLoading(msg: String = "正在加载") {
        _loadingMsg.postValue(msg)
    }

    /**
     * 取消loading框
     */
    fun dismissLoading() {
        _dismissLoading.postValue(false)
    }
}